#include "net.h"

//udp 服务器

int main()
{

	int fd;
	struct sockaddr_in soc; 
	//创建套接字
	if( (fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		perror("socket");
		exit(1);
	}

	int b_reuse = 1;
    setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &b_reuse, sizeof (int));

	//填充结构体
	soc.sin_family = AF_INET;
	soc.sin_port = htons(PORT);
	soc.sin_addr.s_addr = htonl(INADDR_ANY);
	//绑定
	if((bind(fd, (struct sockaddr*)&soc, sizeof(soc))) <0 )
	{
		perror("bind");
		exit(1);
	}
	printf("udp 服务器启动成功\n");


	char buf[BUFSI];
	struct sockaddr_in sin;
	socklen_t addrlen = sizeof(sin);
	//接收信息
	while(1)
	{

		bzero(buf, BUFSI);
		if(recvfrom(fd, buf, BUFSI-1, 0, (struct sockaddr* )&sin, &addrlen ) < 0)
		{
			perror("recvfrom");
			exit(1);
		}
		//获取对方ip地址
		char ip[16];
		if(inet_ntop(AF_INET, &sin.sin_addr, ip, sizeof(sin))  == NULL)
		{
			perror("inet_ntop");
			exit(1);
		}

		printf("client: ip: %s port:%d\n read：%s", ip, ntohs(sin.sin_port),buf);

	}

	close(fd);

	return 0;
}
